package com.rizzo.infrastructure.util;

import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;

public class MatchingUtil {

    /**
     * Will return true if the wildcardPattern matches the input. The wildcard must be provided.
     *
     * @param wildcard        the wildcard contained in the wildcardPattern
     * @param wildcardPattern the pattern with (optional) wildcard
     * @param input           the input to match against
     * @return true if the input matches the wildcardPattern, false otherwise
     */
    public static boolean matchesWildcard(String wildcard, String wildcardPattern, String input) {
        String tempInput = input;
        if (wildcard == null || wildcardPattern == null || input == null) {
            throw new IllegalArgumentException("Arguments cannot be null!");
        }
        if (wildcardPattern.contains(wildcard)) {
            // first check if the start and end are correct if there are no wildcards on either end of the wildcardPattern
            Iterable<String> iterable = Splitter.on(wildcard).omitEmptyStrings().split(wildcardPattern);
            if (!wildcardPattern.startsWith(wildcard)) {
                if (!input.startsWith(Iterables.getFirst(iterable, null))) {
                    return false;
                }
            }
            if (!wildcardPattern.endsWith(wildcard)) {
                if (!input.endsWith(Iterables.getLast(iterable, null))) {
                    return false;
                }
            }
            for (String part : iterable) {
                int idx = tempInput.indexOf(part);
                if (idx == -1) {
                    return false;
                }
                tempInput = tempInput.substring(idx + part.length());
            }
        } else {
            // exact match
            if (!wildcardPattern.equals(input)) {
                return false;
            }
        }
        return true;
    }

}
